'''
Created on 2013-1-11

@author: hanchen
'''
# encoding: utf-8

from ip_addr import ip_str_to_int, ip_int_to_str
from html import get_charset

import urllib
import urllib2

def qq_ip_to_addr(ip):
    url = "http://ip.qq.com/cgi-bin/searchip"
    body = urllib.urlencode({
                    "searchip1": ip
                });
    headers = { 
               "Content-Type": "application/x-www-form-urlencoded"
               };

    # http = httplib2.Http()
    # response = http.request(url, "POST", body, headers)
    # data = response[1]
    request = urllib2.Request(url, body, headers);
    response = urllib2.urlopen(request)
    data = response.read()
    charset = get_charset(data)
    if charset:
        data = data.decode(charset)
    # print data
    begin = data.find("login_show");
    # print begin
    if begin >= 0:
        data = data[begin: begin + 300]
    # return data
    begin = data.find(ip);
    if begin < 0:
        return ""
    begin = data.find("IP");
    begin = data.find("IP", begin + 1);
    data = data[begin: begin + 100]
    begin = data.find("<span>")
    end = data.find("</span>")
    data = data[begin + 6: end]
    data = data.replace("&nbsp;", " ")
    # data = data.decode("gb2312")
    return data

def main():
    bip = ip_str_to_int("100.0.0.1");
    for ip in range(bip, bip + 10):
        s = ip_int_to_str(ip)
        print "%s - %s" % (s, qq_ip_to_addr(s))

if __name__ == '__main__':
    main()
